package com.awenhui.demo.core.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

/**
 * 对应mysql数据库的aes加密,也可用于普通的字符串加密
 *
 * @author yuxf
 * @version 1.0
 * @date 2021/4/8 16:35
 */
public class MysqlAesUtils {
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @return 返回Base64转码后的加密数据
     */
    private static byte[] encrypt(String content,String key) throws Exception {
        if (content == null || content.isEmpty()) return null;
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));// 初始化为加密模式的密码器
        byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
        return encrypted;
    }

    /**
     * 加密并转换为base64编码
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptToBase64(String content,String key) throws Exception {
        byte[] encrypt = encrypt(content, key);
        return new BASE64Encoder().encode(encrypt);
    }

    /**
     * 加密并转换为16进制
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptToHex(String content,String key) throws Exception {
        byte[] encrypt = encrypt(content, key);
        return bytesToHex(encrypt);
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @return
     */
    private static String decrypt(byte[] content,String key) throws Exception {
        if (content == null || content.length==0) return null;
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        //使用密钥初始化，设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
        byte[] original = cipher.doFinal(content);
        String originalString = new String(original, "utf-8");
        return originalString;
    }

    /**
     * 从base64编码解密
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptFromBase64(String content,String key) throws Exception {
        byte[] base64Data =   new BASE64Decoder().decodeBuffer(content);
        String decrypt = decrypt(base64Data, key);
        return decrypt;

    }
    /**
     * 从base64编码解密
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptFromHex(String content,String key) throws Exception {
        byte[] byteData =  hexToBytes(content);
        String decrypt = decrypt(byteData, key);
        return decrypt;

    }


    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String password) throws Exception {
        byte[] keyBytes = Arrays.copyOf(password.getBytes("ASCII"), 16);
        return    new SecretKeySpec(keyBytes, KEY_ALGORITHM);// 转换为AES专用密钥
    }

    /**
     * 字节数组转换为16进制字符串
     * @param buf
     * @return
     */
    private static String bytesToHex(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 16进制转byte数组
     * @param hexString
     * @return
     */
    private static byte[] hexToBytes(String hexString) {
        char[] hex = hexString.toCharArray();
        int length = hex.length / 2;
        byte[] rawData = new byte[length];
        for (int i = 0; i < length; i++) {
            //先将hex数据转10进制数值
            int high = Character.digit(hex[i * 2], 16);
            int low = Character.digit(hex[i * 2 + 1], 16);
            //将第一个值的二进制值左平移4位,ex: 00001000 => 10000000 (8=>128)
            //然后与第二个值的二进制值作联集ex: 10000000 | 00001100 => 10001100 (137)
            int value = (high << 4) | low;
            //与FFFFFFFF作补集
            if (value > 127) value -= 256;
            rawData [i] = (byte) value;
        }
        return rawData ;
    }


    public static void main(String[] args) throws Exception {
        String key="ktwl@123";
        String content="于大新";
        String encrypt = encryptToHex(content, key);
        System.out.println("加密后："+encrypt);
        String decrypt = decryptFromHex(encrypt, "ktwl@123");
        System.out.println("解密后："+decrypt);
        System.out.println("select TO_BASE64(AES_ENCRYPT('"+content+"','"+key+"'))");
        System.out.println("select cast(aes_decrypt(from_base64('"+encrypt+"'),'"+key+"') as char)");

    }
}